<template>
  <div>
    <el-button type="primary" @click="addPermission">新增权限</el-button>
    <el-table :data="list">
      <el-table-column prop="id" label="#" />
      <el-table-column prop="code" label="编码" />
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="remark" label="描述" />
      <el-table-column prop="createdAt" label="创建时间" />
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button @click="editPermission(scope.row)">编辑</el-button>
          <el-button @click="deletePermission(scope.row.id)" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination v-model:current-page="page" v-model:page-size="size" :page-sizes="[10, 20, 50, 100]" :size="size"
      :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="getList"
      @current-change="getList" />

    <my-dialog :title="dialogTitle" ref="dialogRef" @opened="handleDialogOpened" @confirm="submitForm"
      @closed="handleDialogClosed">
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
        <el-form-item label="ID" prop="id" v-if="editId">
          <el-input v-model="editId" disabled />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="ruleForm.code" />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="ruleForm.remark" :rows="2" type="textarea" />
        </el-form-item>
      </el-form>
    </my-dialog>
  </div>
</template>

<script lang="ts" setup>
import {createPermissionApi, deletePermissionApi, getPermissionApi, getPermissionListApi, updatePermissionApi} from '@/api/permission';
import {ref, onMounted, reactive} from 'vue';
import type {PermissionCreateDto, PermissionListDto, PermissionSingleDto} from '@/dtos/permission.dto';
import type {FormInstance, FormRules} from 'element-plus';
import MyDialog from '@/components/dialog/my-dialog.vue'; // 添加此行以导入 MyDialog

const list = ref<PermissionListDto[]>([]);
const total = ref(0);
const page = ref(1);
const size = ref(10);

const getList = async () => {
  const res = await getPermissionListApi({page: page.value, size: size.value})
  list.value = res.list;
  total.value = res.total;
};

const editId = ref<string>("")
const dialogRef = ref<InstanceType<typeof MyDialog>>();
const dialogTitle = ref<string>("编辑权限")
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<PermissionCreateDto>({
  name: '',
  code: '',
  remark: ''
})

const rules = reactive<FormRules<PermissionSingleDto>>({
  name: [
    {required: true, message: '请输入名称', trigger: 'blur'},
  ],
  code: [
    {required: true, message: '请输入编码', trigger: 'blur'},
  ],
})

const submitForm = async () => {
  await ruleFormRef.value?.validate((valid, fields) => {
    if (valid)
    {
      if (editId.value)
        updatePermissionApi(editId.value, {
          name: ruleForm.name,
          code: ruleForm.code,
          remark: ruleForm.remark
        }).then(() => {
          dialogRef.value?.closeDialog()
          getList()
        })
      else
        createPermissionApi({
          name: ruleForm.name,
          code: ruleForm.code,
          remark: ruleForm.remark
        }).then(() => {
          dialogRef.value?.closeDialog()
          getList()
        })
    } else
    {
      console.log('error submit!', fields)
    }
  })
}

const handleDialogOpened = () => {
  if (editId.value)
  {
    dialogTitle.value = "编辑权限"
    getPermissionApi(editId.value).then((res) => {
      Object.assign(ruleForm, res)
    })
  } else
  {
    dialogTitle.value = "新增权限"
    Object.assign(ruleForm, {id: '', name: '', code: '', remark: ''})
  }
}

const handleDialogClosed = () => {
  ruleFormRef.value?.resetFields()
}

const addPermission = () => {
  editId.value = ''
  dialogRef.value?.openDialog()
}

const editPermission = (row: PermissionListDto) => {
  // 编辑权限的逻辑
  editId.value = row.id
  dialogRef.value?.openDialog()
};

const deletePermission = async (id: string) => {
  // 删除权限的逻辑
  ElMessageBox.confirm("确定要删除吗？", '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deletePermissionApi(id).then(() => {
      getList()
    })
  }).catch(() => {
    console.log('已取消删除');
  });
};


onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped></style>